﻿using Device.Domain;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Device.Infrstructre
{
    public class BaseRepository<T> : IRepository<T> where T : class, new()
    {
        private readonly EFCoreDBontext _context;
        public BaseRepository(EFCoreDBontext context)
        {
            _context = context;
        }
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="item">要添加的实体</param>
        /// <returns>返回受影响行数</returns>
        public async Task<int> AddAsync(T item)
        {
            _context.Add(item);
            return await _context.SaveChangesAsync();
        }
        /// <summary>
        /// 列表显示
        /// </summary>
        /// <returns>返回满足条件的数据</returns>
        public async Task<List<T>> GetAllAsync()
        {
            return await _context.Set<T>().ToListAsync();
        }
        /// <summary>
        /// 带条件的列表显示
        /// </summary>
        /// <param name="predicate">查询条件</param>
        /// <returns>返回满足条件的数据</returns>
        public async Task<List<T>> GetAsync(Expression<Func<T, bool>> predicate)
        {
            return await _context.Set<T>().Where(predicate).ToListAsync();
        }
        /// <summary>
        /// 反填
        /// </summary>
        /// <param name="id">要反填的实体id</param>
        /// <returns>返回满足条件的数据</returns>
        public async Task<T> GetModelAsync(int id)
        {
            return await _context.Set<T>().FindAsync(id);
        }
        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="item">要修改的实体</param>
        /// <returns>返回受影响行数</returns>
        public async Task<int> UpdateAsync(T item)
        {
            _context.Update(item);
            return await _context.SaveChangesAsync();
        }
    }
}
